package com.fengze.shop.common.config;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import com.fengze.shop.common.cache.ConfigConstant;
import lombok.Getter;
import lombok.Setter;
import org.jdom.Element;

/**
 * 配置项为多个的时候使用
 * 
 * @author zhanglingsi
 */
public class ArrayItem extends AbstractItem implements Serializable {

    private static final long serialVersionUID = -8161876370554053081L;

    @Getter
    @Setter
    private String sb;

    public ArrayItem() {
        this.element = new Element(ConfigConstant.ARRAY_CONFIG_ITEM);
    }

    public ArrayItem(Element element) {
        this.element = element;
    }

    public ArrayItem(String name) {
        this();
        this.element.addContent(new Element(ConfigConstant.NAME));
        this.element.getChild(ConfigConstant.NAME).setText(name);
    }

    public ArrayItem(String name, String description) {
        this(name);
        this.element.addContent(new Element(ConfigConstant.DESCRIPTION));
        this.element.getChild(ConfigConstant.DESCRIPTION).setText(description);
    }

    public void addValue(String value) {
        Element temp = new Element(ConfigConstant.ARRAY_VALUE);
        temp.addContent(value);
        element.addContent(temp);
    }

    public String[] getValueList() {
        List list = this.element.getChildren(ConfigConstant.ARRAY_VALUE);
        String[] avs = new String[list.size()];
        Iterator itrts = list.iterator();
        int i = 0;
        while (itrts.hasNext()) {
            Element ele = (Element) itrts.next();
            avs[i++] = ele.getText();
        }
        return avs;
    }

    public void modify(ArrayItem arrayItem) {
        this.setDescription(arrayItem.getDescription());
        //Remove all old array values
        this.element.removeChildren(ConfigConstant.ARRAY_VALUE);
        //Add new array values
        String[] valueList = arrayItem.getValueList();
        if (valueList != null && valueList.length > 0) {
            for (int i = 0; i < valueList.length; i++) {
                Element temp = new Element(ConfigConstant.ARRAY_VALUE);
                temp.setText(valueList[i]);
                this.element.addContent(temp);
            }
        }
    }
}
